// pagesDoctor/doctorIndex/index.js
import {
  ApiinProgressOrder,
  ApiinCompleteOrder
} from '../../api/docIndex'
import {
  formatDate,
  debounce
} from "../../utils/util"
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    consultation_type: '图文问诊',
    $path: app.globalData.$path,
    activeNames: '1',
    loading: false,
    order_type: '图文问诊',
    param: {
      page: 1,
      size: 100,
      finish: false,
    }
  },







  //点击消息
  messageClick(e) {
    const item = e.currentTarget.dataset.v
    const type = e.currentTarget.dataset.type
    wx.setStorageSync('comment', item.comment)
    const ops = {
      icon: item.icon,
      id: item.id,
      doctor_id: item.message.patient_id,
      doctor_name: item?.patient?.name,
      department_name: item.department_name,
      consultation_order_id: item.message.consultation_order_id,
      comment: item.comment,
      statusS: item.statusS,
      order_time: item.order_time,
      status: type ? '3' : item.status,
      finish_time: item.finish_time,
      cancel_time: item.cancel_time,
      uid: item.uid,
      patient_id: item.patient_id
    }

    wx.setStorageSync('messageDetail', ops)
    wx.navigateTo({
      url: `/pagesDoctor/messageDetail/index?contact=${JSON.stringify(ops)}`,
    })
  },


  //加载更多
  onLoadMore() {
    if (this.data.loading || this.data.param.finish) return
    this.data.param.page += 1
    this.getComplete()
  },


  onChange(event) {
    console.log(event)
    this.setData({
      activeNames: event.detail.name,
    });
    if (event.detail.name == '2') {
      this.getComplete()
    } else {
      this.getInProgress()
    }
  },

  onChangeTab(e) {
    this.setData({
      consultation_type: e.detail.title
    })
    /*   this.getInProgress(this.data.consultation_type, this.data.order_type) */
  },

  onChangeOrder_type(e) {
    this.setData({
      order_type: e.detail.title
    })
    /*   this.getInProgress(this.data.consultation_type, this.data.order_type) */
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.setData({
      userInfo: wx.getStorageSync('userInfo')
    })
    //判断如果是不同的角色改变不同的值consultation_type

    if (this.data.userInfo.type == '药师') {
      this.setData({
        consultation_type: '药师咨询'
      })
    } else if (this.data.userInfo.type == '护士') {
      this.setData({
        consultation_type: '图文问诊'
      })
    }
  },
  onShow(options) {
    this.getTabBar().init();
    /*   this.getInProgress() */
    /*     this.getComplete() */
    this.getInProgress()
    /*   app.ws.onList(true, this.getInProgressData.bind(this)) */
  },
  //获取进行中的数据
  getInProgressData() {
    let val = wx.getStorageSync('webData')
    const index = this.findLeftDataIndex(val.consultation_order_id)
    if (index > 0) {
      this.data.orderList[0].unshift(this.data.orderList[0].splice(index, 1)[0])
    }
    this.data.orderList.forEach(item => {
      //判断是否有新消息提示
      item.forEach(i => {
        if (i.id == val.consultation_order_id) {
          i.message.last_message = val.content
          i.message.type = val.type
          i.message.doctor_notice = '1'
          this.setData({
            is_patient_notice: true
          })
        }
      })
    })
    this.setData({
      orderList: this.data.orderList
    })

  },


  findLeftDataIndex(webId) {
    return this.data.orderList[0].findIndex(item => item.id === webId)
  },
  getComplete() {
    this.setData({
      loading: true
    })
    //保存上一次的page
    let completeData
    ApiinCompleteOrder(this.data.param).then(res => {
      const data = res.data
      /*   for (let i = 0; i < data.length; i++) {
          if (data[i].order_time == data[i + 1].order_time) {
            data[i].push('1')
          }
        } */
      /*   data.forEach(item => {
          if (item[0].order_time = item[0].order_time) {

          }
        }) */
      completeData = this.data.param.page === 1 ? data : this.data.completeData.concat(data)
      if (data.length == 0) {
        this.data.param.finish = true
      }
      /*      this.data.param.finish = completeData.length >= res.page.total */
      this.setData({
        completeData,
        loading: false
      })

    })
  },

  getInProgress(consultation_type, order_type) {
    wx.showLoading({
      title: '加载中'
    })
    ApiinProgressOrder().then(res => {
      res.data.orderList.forEach(item => {
        let arr = item.map(i => {
          return i.message.patient_notice
        })
        if (arr.indexOf('1') == '-1') {
          this.setData({
            is_patient_notice: false
          })
        } else {
          this.setData({
            is_patient_notice: true
          })
        }
      })



      /*   let val1 = res.data.orderList.find(item => {
          return item[0].order_type == this.data.consultation_type
        })
        console.log(val1) */
      let data = [{
          text: '图文问诊',
          count: 0,
          data: []
        }, {
          text: '视频问诊',
          count: 0,
          data: []
        }, {
          text: '首诊咨询',
          count: 0,
          data: []
        },
        {
          text: '药师咨询',
          count: 0,
          data: []
        },
        {
          text: '团队问诊',
          count: 0,
          data: []
        },
        {
          text: '护理咨询',
          count: 0,
          data: []
        },
      ]

      /*     const result = res.data.orderList.map(arr => arr.filter(item => item.order_type === '视频问诊')).filter(arr => arr.length > 0); */
      data.forEach(iv => {
        let val = res.data.orderList.map(arr => arr.filter(item => item.order_type === iv.text)).filter(arr => arr.length > 0);
        const totalCount = val.reduce((count, arr) => count + arr.length, 0);
        iv.data = val
        iv.count = totalCount
      })


      /*  res.data.orderList.forEach(item => {
         data.forEach(i => {
           if (item[0].order_type == i.text) {
             i.data.push(item)
             i.count = i.data.length
           }

         })
       }) */
      console.log(data, 'data')
      this.setData({
        count: res.data.count,
        orderList: res.data.orderList,
        dataVal: data
      })
      wx.hideLoading()
    })
  },


  formatText(status) {
    let val = this.isCurrentTimeInRange(status)
    if (val) {
      return '未开始'
    }
    /*  console.log('statusstatusstatus', status)
     if (status == '1') {
       return '待接诊'
     } else if (status == '3') {
       return '已结束'
     } */
  },
  //判断当前时间是否再字符串内
  isCurrentTimeInRange(timeRangeStr) {
    // 解析输入的时间范围字符串 '2024-12-04 13:47-15:00'
    const [dateStr, timeRange] = timeRangeStr.split(' '); // 拆分日期和时间范围

    // 拆分开始时间和结束时间
    const [startTimeStr, endTimeStr] = timeRange.split('-');

    // 构造完整的日期时间字符串并转为 Date 对象
    const startDateTime = new Date(`${dateStr}T${startTimeStr}:00`);
    const endDateTime = new Date(`${dateStr}T${endTimeStr}:00`);

    // 获取当前时间
    const currentTime = new Date();

    // 判断当前时间是否在范围内
    return currentTime < startDateTime
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})